import { defineStore } from 'pinia'
import { reqCategory1Info, reqCategory2Info, reqCategory3Info } from '@/api/category'
import type { category1ListType, category2ListType, category3ListType } from '@/api/category'

interface stateType {
  category1list: category1ListType;
  category2list: category2ListType;
  category3list: category3ListType;
  category1Id: number | null,
  category2Id: number | null,
  category3Id: number | null,
}
export default defineStore('category', {
  state: (): stateType => {
    return {
      category1list: [],
      category2list: [],
      category3list: [],

      category1Id: null,
      category2Id: null,
      category3Id: null,
    }
  },
  actions: {
    // 获取一级分类
    async getCategory1List() {
      try {

        const res = await reqCategory1Info()
        this.category1list = res
      } catch (error) {
        return Promise.reject(error)
      }
    },
    // 获取二级分类
    async getCategory2List() {
      try {
        this.category2list = [];
        this.category3list = [];
        this.category2Id = null;
        this.category3Id = null;

        const res = await reqCategory2Info(this.category1Id!)
        this.category2list = res
      } catch (error) {
        return Promise.reject(error)
      }
    },
    // 获取二级分类
    async getCategory3List() {
      try {
        this.category3list = [];
        this.category3Id = null;
        const res = await reqCategory3Info(this.category2Id!)
        this.category3list = res
      } catch (error) {
        return Promise.reject(error)
      }
    },
  }

})